//
//  ViewController.m
//  CarNetwork
//
//  Created by fzuacm on 16/4/17.
//  Copyright © 2016年 fzu_z. All rights reserved.
//

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<MKMapViewDelegate,CLLocationManagerDelegate,UITextFieldDelegate>
{
    MKMapView *_mapView;
    CLLocationManager *_locationManager;
    UITextField *desitinationTextField;
    CLLocationCoordinate2D coordinate;
}
@property(nonatomic,strong)CLGeocoder *geocoder;
@property(nonatomic,strong)MKPolyline *navigationPath;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addGesture];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self.navigationController setNavigationBarHidden:YES];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initMap];
    
    [self createNavItem];
}

-(void)addGesture
{
    UITapGestureRecognizer *tap1=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewtaped:)];
    tap1.cancelsTouchesInView=NO;
    [self.view addGestureRecognizer:tap1];
}

-(void)initMap
{
    _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _mapView.userTrackingMode = MKUserTrackingModeFollow;
    _mapView.mapType = MKMapTypeStandard;
    _mapView.scrollEnabled=YES;
    _mapView.rotateEnabled=YES;
    _mapView.zoomEnabled=YES;
    _mapView.showsUserLocation=YES;
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
    
    if (!self.geocoder) {
        self.geocoder=[[CLGeocoder alloc] init];
    }
    if (!self.navigationPath) {
        self.navigationPath=[[MKPolyline alloc] init];
    }
    
    _locationManager = [[CLLocationManager alloc] init];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        [_locationManager requestWhenInUseAuthorization];
        [_locationManager requestAlwaysAuthorization];
    }
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        _locationManager.allowsBackgroundLocationUpdates = YES;
    }
    
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    _locationManager.delegate = self;
    CLLocationDistance distance = 10.0;
    _locationManager.distanceFilter = distance;
    
    [_locationManager startUpdatingLocation];
    
}

-(void)locateToLatitude:(CGFloat)latitude andLongitude:(CGFloat)longitude
{
    CLLocationCoordinate2D center ={latitude,longitude};
    MKCoordinateSpan span;
    span.latitudeDelta=0.03;
    span.longitudeDelta=0.03;
    
    MKCoordinateRegion regin={center,span};
    [_mapView setRegion:regin animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createNavItem
{
    UIButton *locationButton;
    locationButton = [UIButton buttonWithType:UIButtonTypeSystem];
    locationButton.frame=CGRectMake(20, 450, 40, 40);
    [locationButton setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"location.png"]] forState:UIControlStateNormal];
    locationButton.tag=101;
    [locationButton addTarget:self action:@selector(clickToolBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:locationButton];
    
    UILabel *goLabel;
    goLabel=[[UILabel alloc] initWithFrame:CGRectMake(20, 30, 40, 40)];
    goLabel.text=@"到:";
    goLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:goLabel];

    
    desitinationTextField=[[UITextField alloc] initWithFrame:CGRectMake(70, 30, 180, 40)];
    desitinationTextField.delegate = self;
    desitinationTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:desitinationTextField];
    
    UIButton *navButton;
    navButton = [UIButton buttonWithType:UIButtonTypeSystem];
    navButton.frame=CGRectMake(260, 30, 40, 40);
    [navButton setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"nav.png"]] forState:UIControlStateNormal];
    navButton.tag=102;
    [navButton addTarget:self action:@selector(clickToolBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:navButton];
}

-(void)clickToolBtn:(UIButton *)btn
{
    switch (btn.tag) {
        case 101:
        {
            [self locateToLatitude:coordinate.latitude andLongitude:coordinate.longitude];
            
        }
            break;
        case 102:
        {
            [self startNavgation];
        }
            break;
        default:
            break;
    }
}

-(void)viewtaped:(UIGestureRecognizer *)tap1
{
    [self.view endEditing:YES];
}

-(void)startNavgation
{
    NSString  *destAddress=desitinationTextField.text;

    if (destAddress.length) {
        //解析用户输入地址
        [self.geocoder geocodeAddressString:destAddress completionHandler:^(NSArray *placemarks,NSError *error)
         {
             if(placemarks)
             {
                 //NSLog(@"success");
                 for (CLPlacemark *placemark in placemarks) {
                     //delete last nav
                     [_mapView removeOverlay:self.navigationPath];
                     NSLog(@"目的地:%@,城市:%@,国家:%@",placemark.name,placemark.locality,placemark.country);
                     //create request
                     MKDirectionsRequest *request=[[MKDirectionsRequest alloc] init];
                     //begin your locate
                     request.source=[MKMapItem mapItemForCurrentLocation];
                     //desitination
                     CLPlacemark *pl = placemarks[0];
                     CLPlacemark *placemark = [[CLPlacemark alloc] initWithPlacemark:pl];
                     MKPlacemark *place = [[MKPlacemark alloc] initWithPlacemark:placemark];
                     request.destination=[[MKMapItem alloc] initWithPlacemark:place];
                     
                     MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
                     
                     //get information of nav
                     [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *responses,NSError *error)
                      {
                          MKRoute *route=responses.routes[0];
                          self.navigationPath=route.polyline;
                          [_mapView addOverlay:self.navigationPath level:MKOverlayLevelAboveLabels];
                      }];
                     
                 }
             }
         }];
        
    }
}



#pragma delegate
//
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = [locations firstObject];
    NSLog(@"%@",location);
    coordinate = location.coordinate;
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    //NSLog(@"%@",userLocation);
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//show nav
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    MKPolylineRenderer *renderer=[[MKPolylineRenderer alloc] initWithPolyline:overlay];
    renderer.strokeColor=[UIColor redColor];
    renderer.lineWidth=2.0;
    return renderer;
}
@end

